    var curUserId = null;
//    var curChatUserId = null;
    var conn = null;
    var curRoomId = null;
    var msgCardDivId = "chat01";
    var talkToDivId = "talkTo";
    var talkInputId = "talkInputId";
    var fileInputId = "fileInput";
    var bothRoster = [];
    var toRoster = [];
    var maxWidth = 200;
    var groupFlagMark = "group--";
    var groupQuering = false;
    var textSending = false;
    var time = 0;
    var swfupload = null;
    var flashFilename = '';
    var audioDom = [];
    window.URL = window.URL || window.webkitURL || window.mozURL
            || window.msURL;
    var getLoginInfo = function() {
        return {
            isLogin : false
        };
    };
    var showLoginUI = function() {
        $('#loginmodal').modal('show');
        $('#username').focus();
    };
    var showWaitLoginedUI = function() {
        $('#waitLoginmodal').modal('show');
    };
    var hiddenWaitLoginedUI = function() {
        $('#waitLoginmodal').modal('hide');
    };
    var showChatUI = function() {
        $('#content').css({
            "display" : "block"
        });
    };
    //定义消息编辑文本域的快捷键，enter和ctrl+enter为发送，alt+enter为换行
    //控制提交频率
    $(function() {
        // $(document).ready(function(){
        //     login()
        // });
        $("textarea").keydown(function(event) {
            if (event.altKey && event.keyCode == 13) {
                e = $(this).val();
                $(this).val(e + '\n');
            } else if (event.ctrlKey && event.keyCode == 13) {
                //e = $(this).val();
                //$(this).val(e + '<br>');
                event.returnValue = false;
                sendText();
                return false;
            } else if (event.keyCode == 13) {
                event.returnValue = false;
                sendText();
                return false;
            }
        });
        $("#usetoken").on("click", function(){
            if ($("#password").attr("disabled")) {
                $("#password").removeAttr("disabled");
            } else {
                $("#password").attr("disabled", "disabled");
            }
            if ($("#token").attr("disabled")) {
                $("#token").removeAttr("disabled");
            } else {
                $("#token").attr("disabled", "disabled");
            }
        });
    });
    //easemobwebim-sdk注册回调函数列表
    $(document).ready(function() {
        handleConfig();
        conn = new Easemob.im.Connection();
        //初始化连接
        conn.init({
            https : Easemob.im.config.https,
            url: Easemob.im.config.xmppURL,
            //当连接成功时的回调方法
            onOpened : function() {
                handleOpen(conn);
            },
            //当连接关闭时的回调方法
            onClosed : function() {
                handleClosed();
            },
            //收到文本消息时的回调方法
            onTextMessage : function(message) {
                handleTextMessage(message);
            },
            //收到表情消息时的回调方法
            onEmotionMessage : function(message) {
                handleEmotion(message);
            },
            //收到图片消息时的回调方法
            onPictureMessage : function(message) {
                handlePictureMessage(message);
            },
            //收到音频消息的回调方法
            onAudioMessage : function(message) {
                handleAudioMessage(message);
            },
            //收到位置消息的回调方法
            onLocationMessage : function(message) {
                handleLocationMessage(message);
            },
            //收到文件消息的回调方法
            onFileMessage : function(message) {
                handleFileMessage(message);
            },
            //收到视频消息的回调方法
            onVideoMessage : function(message) {
                handleVideoMessage(message);
            },
            //收到联系人订阅请求的回调方法
            onPresence : function(message) {
                handlePresence(message);
            },
            //收到联系人信息的回调方法
            onRoster : function(message) {
                handleRoster(message);
            },
            //收到群组邀请时的回调方法
            onInviteMessage : function(message) {
                handleInviteMessage(message);
            },
            //异常时的回调方法
            onError : function(message) {
                handleError(message);
            }
        });
        // 登录
        login();
    });
    var handleConfig = function() {
        if(Easemob.im.Helper.getIEVersion() < 10) {
            Easemob.im.config.https = location.protocol == 'https:' ? true : false;
            if(!Easemob.im.config.https) {
                if(Easemob.im.config.xmppURL.indexOf('https') == 0) {
                    Easemob.im.config.xmppURL = Easemob.im.config.xmppURL.replace(/^https/, 'http');
                }
                if(Easemob.im.config.apiURL.indexOf('https') == 0) {
                    Easemob.im.config.apiURL = Easemob.im.config.apiURL.replace(/^https/, 'http');
                }
            } else {
                if(Easemob.im.config.xmppURL.indexOf('https') != 0) {
                    Easemob.im.config.xmppURL = Easemob.im.config.xmppURL.replace(/^http/, 'https');
                }
                if(Easemob.im.config.apiURL.indexOf('https') != 0) {
                    Easemob.im.config.apiURL = Easemob.im.config.apiURL.replace(/^http/, 'https');
                }
            }
        }
    }
    //处理连接时函数,主要是登录成功后对页面元素做处理
    var handleOpen = function(conn) {
        //从连接中获取到当前的登录人注册帐号名
        curUserId = conn.context.userId;
        conn.setPresence();//设置用户上线状态，必须调用
        //获取当前登录人的联系人列表
        conn.getRoster({
            success : function(roster) {
                // 页面处理
                hiddenWaitLoginedUI();
                showChatUI();
                var curroster;
                for ( var i in roster) {
                    var ros = roster[i];
                    //both为双方互为好友，要显示的联系人,from我是对方的单向好友
                    if (ros.subscription == 'both'
                            || ros.subscription == 'from') {
                        bothRoster.push(ros);
                    } else if (ros.subscription == 'to') {
                        //to表明了联系人是我的单向好友
                        toRoster.push(ros);
                    }
                }
                if (bothRoster.length > 0) {
                    curroster = curChatUserId;
//                    buildContactDiv("contractlist", bothRoster);//联系人列表页面处理
                    if (curChatUserId){
                     conn.setPresence();
                        setCurrentContact(curChatUserId);//页面处理将第一个联系人作为当前聊天div
                    }
                }
            }
        });
        //启动心跳
        if (conn.isOpened()) {
            conn.heartBeat(conn);
        }
    };
    //连接中断时的处理，主要是对页面进行处理
    var handleClosed = function() {
        curUserId = null;
        curChatUserId = null;
        curRoomId = null;
        bothRoster = [];
        toRoster = [];
        for(var i=0,l=audioDom.length;i<l;i++) {alert('here')
            if(audioDom[i].jPlayer) audioDom[i].jPlayer('destroy');
        }
        clearContactUI("contactlistUL", "contactgrouplistUL",
                "momogrouplistUL", msgCardDivId);
        showLoginUI();
        groupQuering = false;
        textSending = false;
    };
    //easemobwebim-sdk中收到联系人订阅请求的处理方法，具体的type值所对应的值请参考xmpp协议规范
    var handlePresence = function(e) {
        //（发送者希望订阅接收者的出席信息），即别人申请加你为好友
        if (e.type == 'subscribe') {
            if (e.status) {
                if (e.status.indexOf('resp:true') > -1) {
                    agreeAddFriend(e.from);
                    return;
                }
            }
            var subscribeMessage = e.from + "请求加你为好友。\n验证消息：" + e.status;
            showNewNotice(subscribeMessage);
            $('#confirm-block-footer-confirmButton').click(function() {
                //同意好友请求
                agreeAddFriend(e.from);//e.from用户名
                //反向添加对方好友
                conn.subscribe({
                    to : e.from,
                    message : "[resp:true]"
                });
                $('#confirm-block-div-modal').modal('hide');
            });
            $('#confirm-block-footer-cancelButton').click(function() {
                rejectAddFriend(e.from);//拒绝加为好友
                $('#confirm-block-div-modal').modal('hide');
            });
            return;
        }
    };
    //异常情况下的处理方法
    var handleError = function(e) {
        e && e.upload && $('#fileModal').modal('hide');
        conn.stopHeartBeat(conn);
    };
    //登录系统时的操作方法
    var login = function() {
        // hiddenLoginUI();
        showWaitLoginedUI();
        //根据用户名密码登录系统
        conn.open({
            apiUrl : Easemob.im.config.apiURL,
            user : easemobUsername,
            pwd : easemobPassword,
            //连接时提供appkey
            appKey : easemobAppKey
        });
        return false;
    };
    //注册新用户操作方法
    var regist = function() {
        var user = $("#regist_username").val();
        var pass = $("#regist_password").val();
        var nickname = $("#regist_nickname").val();
        if (user == '' || pass == '' || nickname == '') {
            alert("用户名/密码/昵称 不能为空");
            return;
        }
        var options = {
            username : user,
            password : pass,
            nickname : nickname,
            appKey : easemobAppKey,
            success : function(result) {
                alert("注册成功!");
                $('#loginmodal').modal('show');
                $('#regist-div-modal').modal('hide');
            },
            error : function(e) {
                alert(e.error);
            },
            apiUrl : Easemob.im.config.apiURL
        };
        Easemob.im.Helper.registerUser(options);
    };
    //注册页面返回登录页面操作
    var showlogin = function() {
        $('#loginmodal').modal('show');
        $('#regist-div-modal').modal('hide');
    };
    var logout = function() {
        conn.stopHeartBeat(conn);
        conn.close();
    };
    //设置当前显示的聊天窗口div，如果有联系人则默认选中联系人中的第一个联系人，如没有联系人则当前div为null-nouser
    var setCurrentContact = function(defaultUserId) {
        showContactChatDiv(defaultUserId);
        if (curChatUserId != null) {
            hiddenContactChatDiv(curChatUserId);
        } else {
            $('#null-nouser').css({
                "display" : "none"
            });
        }
        curChatUserId = defaultUserId;
    };
    //构造当前聊天记录的窗口div
    var getContactChatDiv = function(chatUserId) {
        return document.getElementById(curUserId + "-" + chatUserId);
    };
    //如果当前没有某一个联系人的聊天窗口div就新建一个
    var createContactChatDiv = function(chatUserId) {
        var msgContentDivId = curUserId + "-" + chatUserId;
        var newContent = document.createElement("div");
        $(newContent).attr({
            "id" : msgContentDivId,
            "class" : "chat01_content",
            "className" : "chat01_content",
            "style" : "display:none"
        });
        return newContent;
    };
    //显示当前选中联系人的聊天窗口div，并将该联系人在联系人列表中背景色置为蓝色
    var showContactChatDiv = function(chatUserId) {
        var contentDiv = getContactChatDiv(chatUserId);
        if (contentDiv == null) {
            contentDiv = createContactChatDiv(chatUserId);
            document.getElementById(msgCardDivId).appendChild(contentDiv);
        }
        contentDiv.style.display = "block";
        var contactLi = document.getElementById(chatUserId);
        if (contactLi == null) {
            return;
        }
        contactLi.style.backgroundColor = "#33CCFF";
        var dispalyTitle = null;//聊天窗口显示当前对话人名称
        if (chatUserId.indexOf(groupFlagMark) >= 0) {
            dispalyTitle = "群组" + $(contactLi).attr('displayname') + "聊天中";
            curRoomId = $(contactLi).attr('roomid');
            $("#roomMemberImg").css('display', 'block');
        } else {
            dispalyTitle = "与" + chatUserId + "聊天中";
            $("#roomMemberImg").css('display', 'none');
        }
        document.getElementById(talkToDivId).children[0].innerHTML = dispalyTitle;
    };
    //对上一个联系人的聊天窗口div做隐藏处理，并将联系人列表中选择的联系人背景色置空
    var hiddenContactChatDiv = function(chatUserId) {
        var contactLi = document.getElementById(chatUserId);
        if (contactLi) {
            contactLi.style.backgroundColor = "";
        }
            $('#null-nouser').css({
                "display" : "none"
            });

    };
    //切换联系人聊天窗口div
    var chooseContactDivClick = function(li) {
        var chatUserId = li.id;
        if ($(li).attr("type") == 'groupchat'
                && ('true' != $(li).attr("joined"))) {
            conn.join({
                roomId : $(li).attr("roomId")
            });
            $(li).attr("joined", "true");
        }
        if (chatUserId != curChatUserId) {
            if (curChatUserId == null) {
                showContactChatDiv(chatUserId);
            } else {
                showContactChatDiv(chatUserId);
                hiddenContactChatDiv(curChatUserId);
            }
            curChatUserId = chatUserId;
        }
        //对默认的null-nouser div进行处理,走的这里说明联系人列表肯定不为空所以对默认的聊天div进行处理
        $('#null-nouser').css({
            "display" : "none"
        });
        var badgespan = $(li).children(".badge");
        if (badgespan && badgespan.length > 0) {
            li.removeChild(li.children[2]);
        }
        //点击有未读消息对象时对未读消息提醒的处理
        var badgespanGroup = $(li).parent().parent().parent().find(".badge");
        if (badgespanGroup && badgespanGroup.length == 0) {
            $(li).parent().parent().parent().prev().children().children()
                    .remove();
        }
    };
    var clearContactUI = function(contactlistUL, contactgrouplistUL,
            momogrouplistUL, contactChatDiv) {
        //处理联系人分组的未读消息处理
        var accordionChild = $('#accordionDiv').children();
        for (var i = 1; i <= accordionChild.length; i++) {
            var badgegroup = $('#accordion' + i).find(".badgegroup");
            if (badgegroup && badgegroup.length > 0) {
                $('#accordion' + i).children().remove();
            }
        }
        ;
        //清除右侧对话框内容
        document.getElementById(talkToDivId).children[0].innerHTML = "";
        var chatRootDiv = document.getElementById(contactChatDiv);
        var children = chatRootDiv.children;
        for (var i = children.length - 1; i > 1; i--) {
            chatRootDiv.removeChild(children[i]);
        }
        $('#null-nouser').css({
            "display" : "block"
        });
    };
    var emotionFlag = false;
    var showEmotionDialog = function() {
        if (emotionFlag) {
            $('#wl_faces_box').css({
                "display" : "block"
            });
            return;
        }
        emotionFlag = true;
        // Easemob.im.Helper.EmotionPicData设置表情的json数组
        var sjson = Easemob.im.Helper.EmotionPicData;
        for ( var key in sjson) {
            var emotions = $('<img>').attr({
                "id" : key,
                "src" : sjson[key],
                "style" : "cursor:pointer;"
            }).click(function() {
                selectEmotionImg(this);
            });
            $('<li>').append(emotions).appendTo($('#emotionUL'));
        }
        $('#wl_faces_box').css({
            "display" : "block"
        });
    };
    //表情选择div的关闭方法
    var turnoffFaces_box = function() {
        $("#wl_faces_box").fadeOut("slow");
    };
    var selectEmotionImg = function(selImg) {
        var txt = document.getElementById(talkInputId);
        txt.value = txt.value + selImg.id;
        txt.focus();
    };
    var showSendPic = function() {
        $('#fileModal').modal('toggle');
        $('#sendfiletype').val('pic');
        $('#send-file-warning').html("");
        uploadType = 'pic';
    };
    var showSendAudio = function() {
        $('#fileModal').modal('toggle');
        $('#sendfiletype').val('audio');
        $('#send-file-warning').html("");
        uploadType = 'audio';
    };
    var sendText = function() {
        if (textSending) {
            return;
        }
        $("p2").parent().css({ "overflow": "hidden", "margin-bottom": "15px" });
        textSending = true;
        var msgInput = document.getElementById(talkInputId);
        var msg = msgInput.value;
        if (msg == null || msg.length == 0) {
            return;
        }
        var to = curChatUserId;

        if (to == null) {
            return;
        }
        var ext = {
            realname: user_realname,
            avatar: currentUserAvatar,
            associate_id: post_id
        }
        var options = {
            to : to,
            msg : msg,
            type : "chat",
            ext : ext
        };
        // 群组消息和个人消息的判断分支
        //easemobwebim-sdk发送文本消息的方法 to为发送给谁，meg为文本消息对象
        conn.sendTextMessage(options);
        //当前登录人发送的信息在聊天窗口中原样显示
        saveComment();
        var msgtext = msg.replace(/\n/g, '<br>');
        appendMsg(curUserId, to, msgtext,'',realname,currentUserAvatar);
        turnoffFaces_box();
        msgInput.value = "";
        msgInput.focus();
        setTimeout(function() {
            textSending = false;
        }, 3000);
    };
    
    var saveComment = function(){
            var params = {};
            params['comment'] = $('#talkInputId').val();
            params['creator_id'] = currentUserId;
            params['_token'] = $("#chatToken").val();
            var url =yx_jumpUrl;
            $.post(url,params,function(data){

                }, "json").error(function(data) {
                  var error =  $.parseJSON(data.responseText);
                  // layer.msg(error.error_messages.item_type[0]);
                }).success(function(data) {
                })
    }
    var pictype = {
        "jpg" : true,
        "gif" : true,
        "png" : true,
        "bmp" : true
    };
    var sendFile = function() {
        var type = $("#sendfiletype").val();
        if (type == 'pic') {
            sendPic();
        } else {
            sendAudio();
        }
    };
    //easemobwebim-sdk收到文本消息的回调方法的实现
    var handleTextMessage = function(message) {
        var from = message.from;//消息的发送者
        var mestype = message.type;//消息发送的类型是群组消息还是个人消息
        var messageContent = message.data;//文本消息体
        //TODO  根据消息体的to值去定位那个群组的聊天记录
        var room = message.to;
        if (mestype == 'groupchat') {
            // appendMsg(message.from, message.to, messageContent, mestype,realname);
        } else {
            appendMsg(message.from, message.from, messageContent, mestype, message.ext.realname, message.ext.avatar);
        }
    };
    //easemobwebim-sdk收到表情消息的回调方法的实现，message为表情符号和文本的消息对象，文本和表情符号sdk中做了
    //统一的处理，不需要用户自己区别字符是文本还是表情符号。
    var handleEmotion = function(message) {
        var from = message.from;
        var room = message.to;
        var mestype = message.type;//消息发送的类型是群组消息还是个人消息
        if (mestype == 'groupchat') {
            appendMsg(message.from, message.to, message, mestype);
        } else {
            appendMsg(from, from, message);
        }
    };
    //easemobwebim-sdk收到图片消息的回调方法的实现
    var handlePictureMessage = function(message) {
        var filename = message.filename;//文件名称，带文件扩展名
        var from = message.from;//文件的发送者
        var mestype = message.type;//消息发送的类型是群组消息还是个人消息
        var contactDivId = from;
        if (mestype == 'groupchat') {
            contactDivId = groupFlagMark + message.to;
        }
        var options = message;
        // 图片消息下载成功后的处理逻辑
        options.onFileDownloadComplete = function(response, xhr) {
            var objectURL = Easemob.im.Helper.parseDownloadResponse.call(this, response);
            img = document.createElement("img");
            img.onload = function(e) {
                img.onload = null;
                window.URL && window.URL.revokeObjectURL && window.URL.revokeObjectURL(img.src);
            };
            img.onerror = function() {
                img.onerror = null;
                if (typeof FileReader == 'undefined') {
                    img.alter = "当前浏览器不支持blob方式";
                    return;
                }
                img.onerror = function() {
                    img.alter = "当前浏览器不支持blob方式";
                };
                var reader = new FileReader();
                reader.onload = function(event) {
                    img.src = this.result;
                };
                reader.readAsDataURL(response);
            }
            img.src = objectURL;
            var pic_real_width = options.width;
            if (!pic_real_width || pic_real_width == 0) {
                $("<img/>").attr("src", objectURL).load(function() {
                    pic_real_width = this.width;
                    if (pic_real_width > maxWidth) {
                        img.width = maxWidth;
                    } else {
                        img.width = pic_real_width;
                    }
                    appendMsg(from, contactDivId, {
                        data : [ {
                            type : 'pic',
                            filename : filename || '',
                            data : img
                        } ]
                    });
                });
            } else {
                if (pic_real_width > maxWidth) {
                    img.width = maxWidth;
                } else {
                    img.width = pic_real_width;
                }
                appendMsg(from, contactDivId, {
                    data : [ {
                        type : 'pic',
                        filename : filename || '',
                        data : img
                    } ]
                });
            }
        };
        var redownLoadFileNum = 0;
        Easemob.im.Helper.download(options);
    };
    var handleLocationMessage = function(message) {
        var from = message.from;
        var to = message.to;
        var mestype = message.type;
        var content = message.addr;
        if (mestype == 'groupchat') {
            appendMsg(from, to, content, mestype);
        } else {
            appendMsg(from, from, content, mestype);
        }
    };
    var handleInviteMessage = function(message) {
        var type = message.type;
        var from = message.from;
        var roomId = message.roomid;
        //获取当前登录人的群组列表
        conn.listRooms({
            success : function(rooms) {
                if (rooms) {
                    for (i = 0; i < rooms.length; i++) {
                        var roomsName = rooms[i].name;
                        var roomId = rooms[i].roomId;
                        var existRoom = $('#contactgrouplistUL').children(
                                '#group--' + roomId);
                        if (existRoom && existRoom.length == 0) {
                            var lielem = $('<li>').attr({
                                'id' : groupFlagMark + roomId,
                                'class' : 'offline',
                                'className' : 'offline',
                                'type' : 'groupchat',
                                'displayName' : roomsName,
                                'roomId' : roomId,
                                'joined' : 'false'
                            }).click(function() {
                                chooseContactDivClick(this);
                            });
                            $('<img>').attr({
                                'src' : 'img/head/group_normal.png'
                            }).appendTo(lielem);
                            $('<span>').html(roomsName).appendTo(lielem);
                            $('#contactgrouplistUL').append(lielem);
                        }
                    }
                }
            },
            error : function(e) {
            }
        });
    };
    var cleanListRoomDiv = function cleanListRoomDiv() {
        $('#contactgrouplistUL').empty();
    };
    //显示聊天记录的统一处理方法
    var appendMsg = function(who, contact, message, chattype, realname, avatar) {
        var contactDivId = contact;
        if (chattype && chattype == 'groupchat') {
            contactDivId = groupFlagMark + contact;
        }
        // var contactLi = getContactLi(contactDivId);
        var localMsg = null;
        if (typeof message == 'string') {
            localMsg = Easemob.im.Helper.parseTextMessage(message);
            localMsg = localMsg.body;
        } else {
            localMsg = message.data;
        }
         style = 'left';
         if (realname=='') {realname=='匿名用户'};
         if (user_realname=='') {user_realname=='匿名用户'};
         if(who == curUserId){
            style = 'right';
            var headstr = [ '<img class="img-avatar" src=" '+ avatar + '"  style="float:'+style+';">',
                
                '<p2 style="margin-right: 20px;">' + getLoacalTimeString() + "<b></b><br/></p2>" ];
             // style = 'right';
            // var headstr = [ '<img class="img-avatar" src=" '+ avatar + '"  style="width:54px;height:54px;float:'+style+';">',
                
            //     '<p2>' + getLoacalTimeString() + "<b></b><br/></p2>" ];
         }else{
            var headstr = [ '<img class="img-avatar" src=" '+ avatar + '" style="float:'+style+';">',
                '<p2 style="margin-right: 20px;">' + getLoacalTimeString() + "<b></b><br/></p2>" ];
         }
        $("p2").parent().css({ "overflow": "hidden", "margin-bottom": "15px" });
        var header = $(headstr.join(''))
        var lineDiv = document.createElement("div");
        for (var i = 0; i < header.length; i++) {
            var ele = header[i];
            lineDiv.appendChild(ele);
        }
        var messageContent = localMsg;
        for (var i = 0; i < messageContent.length; i++) {
            var msg = messageContent[i];
            var type = msg.type;
            var data = msg.data;
            
            if (type == "emotion") {
                var eletext = "<p3><img src='" + data + "'/></p3>";
                var ele = $(eletext);
                for (var j = 0; j < ele.length; j++) {
                    lineDiv.appendChild(ele[j]);
                }
            } else if (type == "pic" || type == 'audio' || type == 'video') {
                var filename = msg.filename;
                var fileele = $("<p3>" + filename + "</p3><br>");
                for (var j = 0; j < fileele.length; j++) {
                    lineDiv.appendChild(fileele[j]);
                }
                data.nodeType && lineDiv.appendChild(data);
                if(type == 'audio' && msg.audioShim) {
                    var d = $(lineDiv),
                        t = new Date().getTime();
                    d.append($('<div class="'+t+'"></div>\
                        <button class="play'+t+'">播放</button><button style="display:none" class="play'+t+'">暂停</button>'));
                }
            } else {
                style = 'left';

                $("p2").parent().css({ "overflow": "hidden", "margin-bottom": "25px" });
                if(who == curUserId){
                    style = 'right';
                    var eletext = '<p3 class="rightask chat-content-p3" className="chat-content-p3" style="float:'+style+';">' + data + '<i  class="icon_jiao1" style=""><img src="'+appUrl+'/img/myorder/rightRecord.png"></i></p3>';
                    var ele = $(eletext);
                    // ele[0].setAttribute("class", "chat-content-p3");
                    // ele[0].setAttribute("className", "chat-content-p3");
                }else{
                    style = 'left';
                    var eletext = '<p3 class="leftask chat-content-p3" className="chat-content-p3" style="float:'+style+';">' + data + '<i  class="icon_jiao2" style=""><img src="'+appUrl+'/img/myorder/leftRecord.png"></i></p3>';
                    var ele = $(eletext);
                }

                if (curUserId == who) {
                    ele[0].style.backgroundColor = "";
                }
                for (var j = 0; j < ele.length; j++) {
                    lineDiv.appendChild(ele[j]);
                }
            }
        }
        if (curChatUserId == null && chattype == null) {
            setCurrentContact(contact);
            if (time < 1) {
                $('#accordion3').click();
                time++;
            }
        }
        var msgContentDiv = getContactChatDiv(contactDivId);
        if (curUserId == who) {
            lineDiv.style.textAlign = "right";
        } else {
            lineDiv.style.textAlign = "left";
        }
        var create = false;
        if (msgContentDiv == null) {
            msgContentDiv = createContactChatDiv(contactDivId);
            create = true;
        }
        msgContentDiv.appendChild(lineDiv);
        if (create) {
            document.getElementById(msgCardDivId).appendChild(msgContentDiv);
        }
        if(type == 'audio' && msg.audioShim) {
            setTimeout(function(){
                playAudioShim(d.find('.'+t), data.currentSrc, t);
            }, 0);
        }
        msgContentDiv.scrollTop = msgContentDiv.scrollHeight;
        return lineDiv;
    };
    //添加输入框鼠标焦点进入时清空输入框中的内容
    var clearInputValue = function(inputId) {
        $('#' + inputId).val('');
    };
    var removeFriendDomElement = function(userToDel, local) {
        var contactToDel;
        if (bothRoster.length > 0) {
            for (var i = 0; i < bothRoster.length; i++) {
                if (bothRoster[i].name == userToDel) {
                    contactToDel = bothRoster[i];
                    break;
                }
            }
        }
        if (contactToDel) {
            bothRoster.remove(contactToDel);
        }
        // 隐藏删除好友窗口
        if (local) {
            $('#delFridentModal').modal('hide');
        }
        //删除通讯录
        $('#' + userToDel).remove();
        //删除聊天
        var chatDivId = curUserId + "-" + userToDel;
        var chatDiv = $('#' + chatDivId);
        if (chatDiv) {
            chatDiv.remove();
        }
        if (curChatUserId != userToDel) {
            return;
        } else {
            var displayName = '';
            //将第一个联系人作为当前聊天div
            if (bothRoster.length > 0) {
                curChatUserId = bothRoster[0].name;
                $('#' + curChatUserId).css({
                    "background-color" : "#33CCFF"
                });
                var currentDiv = getContactChatDiv(curChatUserId)
                        || createContactChatDiv(curChatUserId);
                document.getElementById(msgCardDivId).appendChild(currentDiv);
                $(currentDiv).css({
                    "display" : "block"
                });
                displayName = '与' + curChatUserId + '聊天中';
            } else {
                $('#null-nouser').css({
                    "display" : "block"
                });
                displayName = '';
            }
            $('#talkTo').html('<a href="#">' + displayName + '</a>');
        }
    };
    //清除聊天记录
    var clearCurrentChat = function clearCurrentChat() {
        var currentDiv = getContactChatDiv(curChatUserId)
                || createContactChatDiv(curChatUserId);
        currentDiv.innerHTML = "";
    };
    var showRoomMemberList = function showRoomMemberList(occupants) {
        var list = $('#room-member-list')[0];
        var childs = list.childNodes;
        for (var i = childs.length - 1; i >= 0; i--) {
            list.removeChild(childs.item(i));
        }
        for (i = 0; i < occupants.length; i++) {
            var jid = occupants[i].jid;
            var userName = jid.substring(jid.indexOf("_") + 1).split("@")[0];
            var txt = $("<p></p>").text(userName);
            $('#room-member-list').append(txt);
        }
        $('#option-room-div-modal').modal('toggle');
    };
    var showRegist = function showRegist() {
        $('#loginmodal').modal('hide');
        $('#regist-div-modal').modal('toggle');
    };
    var getObjectURL = function getObjectURL(file) {
        var url = null;
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    };
    var getLoacalTimeString = function getLoacalTimeString() {
        var date = new Date();
        var time = date.getHours() + ":" + date.getMinutes() + ":"
                + date.getSeconds();
        return time;
    }
    //查看更多聊天记录
    var page = 1;
    var rows_per_page = 10;
    $(document).on('click', '#comments-list', function(e){
    	$this = $(this);
    	$this.css('display', 'none');
        $("#page").css('display', 'block');
        var commentUrl = rootUrl+'/question/'+post_id+'/comment_list?page='+page+'&rows_per_page='+rows_per_page;
    	var str = '';
        $.get(commentUrl, function(data){
        }, 'json').error(function(data){
        }).success(function(data){
        	obj = data.data.comments;
            console.info(obj)
        	for(var i=0; i<obj.length; i++){
                if(obj[i].creator_id == curUserId){
                    str+='<li class="rightChatRecord">'
                        str+='<div class="ChatRecordimg fr"><img src="'+obj[i].creator_avatar+'" width="54" height="54"></div>'
                        str+='<div class="contentinfo fr">'
                            str+='<i class="Recordicon"></i>'
                            str+='<p class="font12 colorD">'+obj[i].created_at+'</p>'
                            str+='<div class="textContent">'+obj[i].content+'</div>'
                        str+='</div>'
                    str+='</li>'
                    // str+='<dl class="r-interface">'
                    //     str+='<dt class="usimg"><img src="'+obj[i].creator_avatar+'"></dt>'
                    //     str+='<dd style="margin-top:10px"><span class="mane">'+obj[i].creator_name+'</span><label id="created_at" class="dateTime">'+obj[i].created_at+'</label></dd>'
                    //     str+='<dd id="content" class="issuetxt">'
                    //         str+='<i class="icon_jiao"><img src="http://www.elvtuan.com/img/question/icon02.png"></i>'
                    //         str+='<span class="contents">'+obj[i].content+'</span>'
                    //     str+='</dd>'
                    // str+='</dl>'
                }else{
                    str+='<li class="leftChatRecord">'
                        str+='<div class="ChatRecordimg"><img src="'+obj[i].creator_avatar+'" width="54" height="54"></div>'
                        str+='<div class="contentinfo fr">'
                            str+='<i class="Recordicon"></i>'
                            str+='<p class="font12 colorD">'+obj[i].created_at+'</p>'
                            str+='<div class="textContent">'+obj[i].content+'</div>'
                        str+='</div>'
                    str+='</li>'

                    // str+='<dl class="l-interface">'
                    //     str+='<dt class="usimg"><img src="'+obj[i].creator_avatar+'"></dt>'
                    //     str+='<dd style="margin-top:10px"><span class="mane">'+obj[i].creator_name+'</span><span id="created_at" class="dateTime">'+obj[i].created_at+'</span></dd>'
                    //     str+='<dd id="content" class="issuetxt">'
                    //         str+='<i class="icon_jiao"><img src="http://www.elvtuan.com/img/question/icon01.png"></i>'
                    //         str+='<span class="contents">'+obj[i].content+'</span>'
                    //     str+='</dd>'
                    // str+='</dl>'
                }
            }
        	if(obj.length == rows_per_page) $this.css('display', 'block');
        	$("#page").after(str);
            $("#page").css('display', 'none');
        	page++;
        	stopDefault(e);
        });
    });
    